enum LogLevel {
  ERROR, WARN, INFO, DEBUG
}
/*
虽然枚举在运行时的表现就像一个真正的object,

虽然字面量枚举可以用作类型
但直接keyof这个字面量枚举的的表现 和 keyof 普通的typeof oneObject后取得的类型的keyof结果表现是不一致的
// type x = keyof LogLevel; // type x = "toString" | "toFixed" | "toExponential" | "toPrecision" | "valueOf" | "toLocaleString"

So最好还是先typeof一下这个字面量枚举 再使用keyof(将目标对象的所有key(对象属性名而不是值)取出来做成联合类型(不同键名(字符串)组成的联合类型))


let O = {a:1,b:'123'}
type x = typeof O
↓↓↓
type x = {
  a: number;
  b: string;
}
type y = keyof x; //type y = "a" | "b"
let xx:y = "a" √
let xx:y = "axxx" ×
*/

/**
 * This is equivalent to:
 * type LogLevelStrings = 'ERROR' | 'WARN' | 'INFO' | 'DEBUG';
 */
// type x = keyof LogLevel; // type x = "toString" | "toFixed" | "toExponential" | "toPrecision" | "valueOf" | "toLocaleString"
type LogLevelStrings = keyof typeof LogLevel; // type LogLevelStrings = "ERROR" | "WARN" | "INFO" | "DEBUG"

function printImportant(key: LogLevelStrings, message: string) {
  const num = LogLevel[key];
  if (num <= LogLevel.WARN) {
    console.log('Log level key is: ', key);
    console.log('Log level value is: ', num);
    console.log('Log level message is: ', message);
  }
}
printImportant('ERROR', 'This is a message');
